<template>
  <!-- 自定义标题栏 - 仅在非Mac平台显示 -->
  <div v-if="!isMacOS" class="custom-titlebar">
    <div class="titlebar-drag-region"></div>
    <div class="window-controls">
      <button class="window-control minimize" @click="minimizeWindow" title="最小化">
        <svg width="12" height="12" viewBox="0 0 12 12">
          <rect x="2" y="5" width="8" height="2" fill="currentColor"/>
        </svg>
      </button>
      <button class="window-control maximize" @click="maximizeWindow" title="最大化">
        <svg width="12" height="12" viewBox="0 0 12 12">
          <rect x="2" y="2" width="8" height="8" stroke="currentColor" stroke-width="1" fill="none"/>
        </svg>
      </button>
      <button class="window-control close" @click="closeWindow" title="关闭">
        <svg width="12" height="12" viewBox="0 0 12 12">
          <path d="M2 2 L10 10 M10 2 L2 10" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
        </svg>
      </button>
    </div>
  </div>
  
  <div class="app-content" :class="{ 'no-titlebar': isMacOS }">
    <router-view/>
    <!-- 登录弹窗 -->
    <LoginModal />
    <!-- 同步状态提示 -->
    <SyncNotification />
    <!-- 冲突解决器已移除，现在自动解决冲突 -->
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, provide } from 'vue'
import { useTodoStore } from '@/stores/todoStore'
import { useAuthStore } from '@/stores/authStore'
import { useSyncStore } from '@/stores/syncStore'
import LoginModal from '@/components/Auth/LoginModal.vue'
import SyncNotification from '@/components/Common/SyncNotification.vue'
import storageAPI from '@/api/storage'

const todoStore = useTodoStore()
const authStore = useAuthStore()
const syncStore = useSyncStore()
const { syncNow } = syncStore

// ==================== 版本管理 ====================
// 应用版本号 - 统一管理，打包后不会失效
const APP_VERSION = '1.0.7'

// 版本管理对象
const versionManager = {
  // 获取当前版本
  getCurrentVersion: () => APP_VERSION,
  
  // 检查版本更新
  checkForUpdates: async () => {
    try {
      const apiUrl = import.meta.env.VITE_GO_URL || 'http://tasklist.localhost'
      const response = await fetch(`${apiUrl}/api/v1/system/app_version`)
      
      if (response.ok) {
        const data = await response.json()
        const latestVersion = data.app_version
        
        // 比较版本号
        const hasUpdate = compareVersions(latestVersion, APP_VERSION) > 0
        
        return {
          hasUpdate,
          currentVersion: APP_VERSION,
          latestVersion,
          upgradeUrl: 'https://www.ynaa.net/topics/8'
        }
      }
      
      return {
        hasUpdate: false,
        currentVersion: APP_VERSION,
        latestVersion: APP_VERSION,
        upgradeUrl: 'https://www.ynaa.net/topics/8'
      }
    } catch (error) {
      console.warn('检查版本更新失败:', error)
      return {
        hasUpdate: false,
        currentVersion: APP_VERSION,
        latestVersion: APP_VERSION,
        upgradeUrl: 'https://www.ynaa.net/topics/8'
      }
    }
  },
  
  // 比较版本号 (返回 1: v1 > v2, -1: v1 < v2, 0: v1 = v2)
  compareVersions: (v1, v2) => {
    const parts1 = v1.split('.').map(Number)
    const parts2 = v2.split('.').map(Number)
    
    const maxLength = Math.max(parts1.length, parts2.length)
    
    for (let i = 0; i < maxLength; i++) {
      const part1 = parts1[i] || 0
      const part2 = parts2[i] || 0
      
      if (part1 > part2) return 1
      if (part1 < part2) return -1
    }
    
    return 0
  },
  
  // 打开升级页面
  openUpgradePage: () => {
    const upgradeUrl = 'https://www.ynaa.net/topics/8'
    
    try {
      if (window.electronAPI && typeof window.electronAPI.openExternal === 'function') {
        // Electron环境
        window.electronAPI.openExternal(upgradeUrl).catch(error => {
          console.error('Failed to open upgrade URL in Electron:', error)
          window.open(upgradeUrl, '_blank')
        })
      } else {
        // 浏览器环境
        window.open(upgradeUrl, '_blank')
      }
    } catch (error) {
      console.error('Error opening upgrade page:', error)
      try {
        window.open(upgradeUrl, '_blank')
      } catch (fallbackError) {
        console.error('All methods failed to open upgrade URL:', fallbackError)
      }
    }
  }
}

// 比较版本号的辅助函数
function compareVersions(v1, v2) {
  return versionManager.compareVersions(v1, v2)
}

// 提供版本管理器给子组件使用
provide('versionManager', versionManager)

// 检测是否为Mac平台
const isMacOS = ref(false)

// 平台检测函数
function detectPlatform() {
  // 检测是否在Electron环境中
  if (window.electronAPI && window.electronAPI.getPlatform) {
    // 通过Electron API获取平台信息
    window.electronAPI.getPlatform().then(platform => {
      isMacOS.value = platform === 'darwin'
    }).catch(() => {
      // 如果API调用失败，使用浏览器检测
      isMacOS.value = navigator.platform.toLowerCase().includes('mac')
    })
  } else {
    // 在浏览器环境中检测
    isMacOS.value = navigator.platform.toLowerCase().includes('mac') || 
                    navigator.userAgent.toLowerCase().includes('mac')
  }
}

// 窗口控制方法
function minimizeWindow() {
  if (window.electronAPI) {
    window.electronAPI.minimize()
  }
}

function maximizeWindow() {
  if (window.electronAPI) {
    window.electronAPI.maximize()
  }
}

async function closeWindow() {
  try {
    // 在关闭前先同步数据
    await syncNow()
    console.log('数据同步完成，准备关闭应用')
  } catch (error) {
    console.warn('关闭前同步失败，但仍将关闭应用:', error)
  } finally {
    // 无论同步成功与否，都关闭应用
    if (window.electronAPI) {
      window.electronAPI.close()
    }
  }
}

// 冲突解决函数已移除，现在自动解决冲突

// 全局主题初始化
async function initGlobalTheme() {
  try {
    const savedTheme = await storageAPI.getItem('app-theme') || 'captain'
    applyGlobalTheme(savedTheme)
  } catch (error) {
    console.warn('加载全局主题失败:', error)
    applyGlobalTheme('captain')
  }
}

// 应用全局主题
function applyGlobalTheme(themeId) {
  const root = document.documentElement
  
  // 根据主题设置CSS变量
  switch (themeId) {
    case 'default':
      root.style.setProperty('--primary-color', '#374151')
      root.style.setProperty('--primary-hover', '#1f2937')
      root.style.setProperty('--background-color', '#ffffff')
      root.style.setProperty('--surface-color', '#f8f9fa')
      root.style.setProperty('--title-color', '#1f2937')
      root.style.setProperty('--text-primary', '#1f2937')
      root.style.setProperty('--text-secondary', '#6b7280')
      root.style.setProperty('--border-color', '#e5e7eb')
      root.style.setProperty('--shadow-color', 'rgba(0, 0, 0, 0.1)')
      root.style.setProperty('--button-secondary-bg', '#f3f4f6')
      root.style.setProperty('--button-secondary-hover', '#e5e7eb')
      root.style.setProperty('--modal-bg', '#ffffff')
      root.style.setProperty('--modal-overlay', 'rgba(0, 0, 0, 0.5)')
      break
    case 'dark':
      root.style.setProperty('--primary-color', '#6b7280')
      root.style.setProperty('--primary-hover', '#4b5563')
      root.style.setProperty('--background-color', '#1f2937')
      root.style.setProperty('--surface-color', '#374151')
      root.style.setProperty('--title-color', '#ffffff')
      root.style.setProperty('--text-primary', '#f9fafb')
      root.style.setProperty('--text-secondary', '#d1d5db')
      root.style.setProperty('--border-color', '#4b5563')
      root.style.setProperty('--shadow-color', 'rgba(0, 0, 0, 0.3)')
      root.style.setProperty('--button-secondary-bg', '#374151')
      root.style.setProperty('--button-secondary-hover', '#4b5563')
      root.style.setProperty('--modal-bg', '#374151')
      root.style.setProperty('--modal-overlay', 'rgba(0, 0, 0, 0.7)')
      break
    case 'captain':
      root.style.setProperty('--primary-color', '#dc2626')
      root.style.setProperty('--primary-hover', '#b91c1c')
      root.style.setProperty('--background-color', '#ffffff')
      root.style.setProperty('--surface-color', '#f8fafc')
      root.style.setProperty('--title-color', '#ffffff')
      root.style.setProperty('--text-primary', '#1e3a8a')
      root.style.setProperty('--text-secondary', '#475569')
      root.style.setProperty('--border-color', '#e2e8f0')
      root.style.setProperty('--shadow-color', 'rgba(30, 58, 138, 0.1)')
      root.style.setProperty('--button-secondary-bg', '#f1f5f9')
      root.style.setProperty('--button-secondary-hover', '#e2e8f0')
      root.style.setProperty('--modal-bg', '#ffffff')
      root.style.setProperty('--modal-overlay', 'rgba(220, 38, 38, 0.2)')
      break
    case 'zijinhong':
      root.style.setProperty('--primary-color', '#983928')
      root.style.setProperty('--primary-hover', '#7a2d20')
      root.style.setProperty('--background-color', '#fdf8f6')
      root.style.setProperty('--surface-color', '#f9f1ed')
      root.style.setProperty('--title-color', '#983928')
      root.style.setProperty('--text-primary', '#983928')
      root.style.setProperty('--text-secondary', '#146654')
      root.style.setProperty('--border-color', '#e8d5d0')
      root.style.setProperty('--shadow-color', 'rgba(152, 57, 40, 0.15)')
      root.style.setProperty('--button-secondary-bg', '#f9f1ed')
      root.style.setProperty('--button-secondary-hover', '#e8d5d0')
      root.style.setProperty('--modal-bg', '#fdf8f6')
      root.style.setProperty('--modal-overlay', 'rgba(152, 57, 40, 0.2)')
      break
    case 'gaojigan':
      root.style.setProperty('--primary-color', '#EB7A53')
      root.style.setProperty('--primary-hover', '#d96942')
      root.style.setProperty('--background-color', '#fefcf8')
      root.style.setProperty('--surface-color', '#fdf9f2')
      root.style.setProperty('--title-color', '#8B4513')
      root.style.setProperty('--text-primary', '#8B4513')
      root.style.setProperty('--text-secondary', '#D2691E')
      root.style.setProperty('--border-color', '#f5e6d8')
      root.style.setProperty('--shadow-color', 'rgba(235, 122, 83, 0.15)')
      root.style.setProperty('--button-secondary-bg', '#fdf9f2')
      root.style.setProperty('--button-secondary-hover', '#f5e6d8')
      root.style.setProperty('--modal-bg', '#fefcf8')
      root.style.setProperty('--modal-overlay', 'rgba(235, 122, 83, 0.2)')
      break
    case 'fugu':
      root.style.setProperty('--primary-color', '#69929a')
      root.style.setProperty('--primary-hover', '#5a7d84')
      root.style.setProperty('--background-color', '#f8fafa')
      root.style.setProperty('--surface-color', '#f1f5f5')
      root.style.setProperty('--title-color', '#2F4F4F')
      root.style.setProperty('--text-primary', '#2F4F4F')
      root.style.setProperty('--text-secondary', '#8B0000')
      root.style.setProperty('--border-color', '#d9e5e6')
      root.style.setProperty('--shadow-color', 'rgba(105, 146, 154, 0.15)')
      root.style.setProperty('--button-secondary-bg', '#f1f5f5')
      root.style.setProperty('--button-secondary-hover', '#d9e5e6')
      root.style.setProperty('--modal-bg', '#f8fafa')
      root.style.setProperty('--modal-overlay', 'rgba(105, 146, 154, 0.2)')
      break
    case 'fenfen':
      root.style.setProperty('--primary-color', '#FEACB4')
      root.style.setProperty('--primary-hover', '#fe9aa4')
      root.style.setProperty('--background-color', '#fffcfd')
      root.style.setProperty('--surface-color', '#fef8f9')
      root.style.setProperty('--title-color', '#8B008B')
      root.style.setProperty('--text-primary', '#8B008B')
      root.style.setProperty('--text-secondary', '#4169E1')
      root.style.setProperty('--border-color', '#f9e6e9')
      root.style.setProperty('--shadow-color', 'rgba(254, 172, 180, 0.15)')
      root.style.setProperty('--button-secondary-bg', '#fef8f9')
      root.style.setProperty('--button-secondary-hover', '#f9e6e9')
      root.style.setProperty('--modal-bg', '#fffcfd')
      root.style.setProperty('--modal-overlay', 'rgba(254, 172, 180, 0.2)')
      break
    case 'dongfang':
      root.style.setProperty('--primary-color', '#12615E')
      root.style.setProperty('--primary-hover', '#0e4e4c')
      root.style.setProperty('--background-color', '#f6f9f9')
      root.style.setProperty('--surface-color', '#eef5f4')
      root.style.setProperty('--title-color', '#2F4F4F')
      root.style.setProperty('--text-primary', '#2F4F4F')
      root.style.setProperty('--text-secondary', '#B8860B')
      root.style.setProperty('--border-color', '#c7d9d8')
      root.style.setProperty('--shadow-color', 'rgba(18, 97, 94, 0.15)')
      root.style.setProperty('--button-secondary-bg', '#eef5f4')
      root.style.setProperty('--button-secondary-hover', '#c7d9d8')
      root.style.setProperty('--modal-bg', '#f6f9f9')
      root.style.setProperty('--modal-overlay', 'rgba(18, 97, 94, 0.2)')
      break

  }
  
  // 更新番茄钟主题
  updatePomodoroTheme(themeId)
}

// 更新番茄钟主题
function updatePomodoroTheme(themeId) {
  const root = document.documentElement
  
  switch (themeId) {
    case 'default':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #f8f9fa 0%, #e5e7eb 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%)')
      break
    case 'dark':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #374151 0%, #1f2937 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #4b5563 0%, #374151 100%)')
      break
    case 'captain':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #dc2626 0%, #b91c1c 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #1e3a8a 0%, #1e40af 100%)')
      break
    case 'zijinhong':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #983928 0%, #7a2d20 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #146654 0%, #0f4d3f 100%)')
      break
    case 'gaojigan':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #EB7A53 0%, #d96942 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #F7D44C 0%, #e6c43b 100%)')
      break
    case 'fugu':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #69929a 0%, #5a7d84 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #b9130a 0%, #9a0f08 100%)')
      break
    case 'fenfen':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #FEACB4 0%, #fe9aa4 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #99AFE1 0%, #7a9bd8 100%)')
      break
    case 'dongfang':
      root.style.setProperty('--pomodoro-task-bg', 'linear-gradient(135deg, #12615E 0%, #0e4e4c 100%)')
      root.style.setProperty('--pomodoro-free-bg', 'linear-gradient(135deg, #E6C054 0%, #d4ae43 100%)')
      break
  }
}

// 软件关闭前同步数据
const handleBeforeUnload = (event) => {
  try {
    const syncStore = useSyncStore()
    // 只在自动同步启用且当前没有同步时才处理
    if (syncStore.syncState.autoSyncEnabled && !syncStore.syncState.isSyncing) {
      // 在浏览器环境中，尝试进行同步但不阻止关闭
      // 因为beforeunload中的异步操作可能不会完成
      syncNow().catch(error => {
        console.warn('关闭前同步失败:', error)
      })
      
      // 不阻止关闭，让用户可以正常关闭应用
      console.log('正在尝试关闭前同步...')
    }
  } catch (error) {
    console.warn('处理关闭前同步时出错:', error)
  }
}

// 应用初始化
onMounted(async () => {
  console.log('应用启动，开始初始化...')
  
  // 检测平台
  detectPlatform()
  
  // 初始化主题
  await initGlobalTheme()
  
  // 初始化认证状态
  await authStore.initAuth()
  
  // 加载数据
  await todoStore.loadData()
  
  // 添加关闭前同步监听器
  window.addEventListener('beforeunload', handleBeforeUnload)
  
  // 注册 Electron IPC 监听器 - 应用关闭前同步
  if (window.electronAPI && window.electronAPI.onSyncBeforeQuit) {
    window.electronAPI.onSyncBeforeQuit(async () => {
      console.log('收到应用关闭前同步请求')
      try {
        // 执行数据同步
        const result = await syncNow()
        console.log('应用关闭前同步完成:', result)
        // 发送同步完成信号
        window.electronAPI.sendSyncComplete({ success: true, result })
      } catch (error) {
        console.error('应用关闭前同步失败:', error)
        // 发送同步失败信号
        window.electronAPI.sendSyncComplete({ success: false, error: error.message })
      }
    })
    console.log('已注册应用关闭前同步监听器')
  }
  
  // 开发环境下的调试信息
  if (import.meta.env.DEV) {
    console.log('开发模式：初始化完成')
    console.log('登录状态:', authStore.isAuthenticated)
    console.log('清单数量:', todoStore.lists?.length || 0)
    console.log('任务数量:', todoStore.tasks?.length || 0)
  }
  
  // 隐藏加载页面
  const loadingPage = document.getElementById('loadingPage')
  if (loadingPage) {
    loadingPage.style.opacity = '0'
    setTimeout(() => {
      loadingPage.style.display = 'none'
    }, 300)
  }
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  window.removeEventListener('beforeunload', handleBeforeUnload)
})
</script>

<style lang="less">
/* 自定义标题栏样式 */
.custom-titlebar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 32px;
  background: var(--background-color, #ffffff);
  border-bottom: 1px solid var(--border-color, #e5e7eb);
  display: flex;
  align-items: center;
  justify-content: space-between;
  z-index: 9999;
  -webkit-app-region: drag; /* 允许拖拽窗口 */
}

.titlebar-drag-region {
  flex: 1;
  height: 100%;
}

.window-controls {
  display: flex;
  -webkit-app-region: no-drag; /* 按钮区域不允许拖拽 */
}

.window-control {
  width: 46px;
  height: 32px;
  border: none;
  background: transparent;
  color: var(--text-primary, #1f2937);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s ease;
  
  &:hover {
    background-color: var(--button-secondary-hover, #e5e7eb);
  }
  
  &.close:hover {
    background-color: #e53e3e;
    color: white;
  }
}

/* 为应用内容添加顶部边距 */
.app-content {
  margin-top: 32px;
  height: calc(100vh - 32px);
  overflow: hidden;
}

/* Mac平台下无标题栏的样式 */
.app-content.no-titlebar {
  margin-top: 0;
  height: 100vh;
}

/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  overflow: hidden;
}

#app {
  height: 100vh;
  overflow: hidden;
}
</style>
